package com.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.Expose;
import com.bstek.urule.console.DefaultPrincipal;
import com.bstek.urule.console.repository.RepositoryService;
import com.bstek.urule.console.repository.RepositoryServiceImpl;
import com.bstek.urule.console.repository.model.RepositoryFile;
import com.bstek.urule.console.repository.model.ResourceItem;
import com.bstek.urule.console.repository.model.ResourcePackage;

@Component
public class KnowledgedPackagePR {

	@Resource(name = RepositoryService.BEAN_ID)
	private RepositoryService uRuleService;

	@DataProvider
	public List<Map<String, Object>> loadKnowledgedPackage() {
		List<Map<String, Object>> returnValue = new ArrayList<Map<String, Object>>();
		try {
			List<RepositoryFile> repositoryFiles = uRuleService.loadProjects("lcx");
			String project = uRuleService.getProject(repositoryFiles.get(0).getFullPath());// 把项目路径转换成项目名称
			List<ResourcePackage> knowledgedPackages = uRuleService.loadProjectResourcePackages(project);// 根据项目名称获取该项目的下知识包

			for (ResourcePackage rPackage : knowledgedPackages) {
				Map<String, Object> value = new HashMap<String, Object>();
				value.put("id", rPackage.getId());
				value.put("packageName", rPackage.getName());
				value.put("project", rPackage.getProject());
				value.put("createDate", rPackage.getCreateDate());
				returnValue.add(value);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return returnValue;
	}

	@DataProvider
	public List<Map<String, Object>> loadKnowledgedPackageItem(String packageId) {
		List<Map<String, Object>> returnValue = new ArrayList<Map<String, Object>>();
		try {
			List<RepositoryFile> repositoryFiles = uRuleService.loadProjects("lcx");
			String project = uRuleService.getProject(repositoryFiles.get(0).getFullPath());// 把项目路径转换成项目名称
			List<ResourcePackage> knowledgedPackages = uRuleService.loadProjectResourcePackages(project);// 根据项目名称获取该项目的下知识包
			for (ResourcePackage rPackage : knowledgedPackages) {
				if (rPackage.getId().equals(packageId)) {
					if (rPackage.getResourceItems() != null) {
						for (ResourceItem item : rPackage.getResourceItems()) {
							Map<String, Object> value = new HashMap<String, Object>();
							value.put("itemName", item.getName());
							value.put("path", item.getPath());
							value.put("packageId", item.getPackageId());
							value.put("version", item.getVersion());
							returnValue.add(value);
						}
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return returnValue;
	}

	/**
	 * 移除知识包中的文件
	 * 
	 * @param paths
	 * @param packageId
	 */
	@Expose
	public void deleteKnowledgeItem(List<String> paths, String packageId) {
		try {
			List<RepositoryFile> repositoryFiles = uRuleService.loadProjects("lcx");
			String project = uRuleService.getProject(repositoryFiles.get(0).getFullPath());// 把项目路径转换成项目名称
			List<ResourcePackage> knowledgedPackages = uRuleService.loadProjectResourcePackages(project);// 根据项目名称获取该项目的下知识包
			List<ResourceItem> items = new ArrayList<ResourceItem>();
			ResourcePackage currentPackage = new ResourcePackage();
			String path = URLEncoder.encode(project, "utf-8") + "/" + RepositoryServiceImpl.RES_PACKGE_FILE;
			StringBuffer xml = new StringBuffer();
			SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			xml.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<res-packages>");
			for (ResourcePackage rPackage : knowledgedPackages) {
				StringBuffer xmlBuffer = new StringBuffer();
				if (rPackage.getId().equals(packageId)) {
					currentPackage = rPackage;
					if (rPackage.getResourceItems() != null) {
						items = rPackage.getResourceItems();
					}
					for (int i = 0; i < items.size(); i++) {
						for (String ppath : paths) {
							if (items.get(i).getPath().equals(ppath)) {
								items.remove(i);
							}
						}
					}
					StringBuffer stbuffer = new StringBuffer();
					for (ResourceItem rItem : items) {
						stbuffer.append("<res-package-item  name=\"" + rItem.getName() + "\" path=\"" + rItem.getPath()
								+ "\" version=\"" + rItem.getVersion() + "\"/>");
					}
					xmlBuffer.append("<res-package id=\"" + currentPackage.getId() + "\" name=\""
							+ currentPackage.getName() + "\" create_date=\"" + sd.format(currentPackage.getCreateDate())
							+ "\" >" + stbuffer + "</res-package>");
				} else {
					StringBuffer stbuffer = new StringBuffer();
					if (rPackage.getResourceItems() != null) {
						for (ResourceItem ritem : rPackage.getResourceItems()) {
							stbuffer.append("<res-package-item  name=\"" + ritem.getName() + "\" path=\""
									+ ritem.getPath() + "\" version=\"" + ritem.getVersion() + "\"/>");
						}
					}
					xmlBuffer.append("<res-package id=\"" + rPackage.getId() + "\" name=\"" + rPackage.getName()
							+ "\" create_date=\"" + sd.format(rPackage.getCreateDate()) + "\" >" + stbuffer
							+ "</res-package>");
				}
				xml.append(xmlBuffer);
			}
			xml.append("</res-packages>");
			uRuleService.saveFile(path, xml.toString(), false, (String) null, this.getDefaultPrincipal());
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private DefaultPrincipal getDefaultPrincipal() {
		DefaultPrincipal principal = new DefaultPrincipal();
		principal.setCompanyId(ContextHolder.getLoginUser().getCompanyId());
		principal.setName(ContextHolder.getLoginUserName());
		principal.setDisplayName(ContextHolder.getLoginUser().getCname());
		return principal;
	}

}
